import React, { Component } from 'react';
import { DatePicker, Input, Table, Form, Tabs, FormInstance, Space } from 'antd';
const { TabPane } = Tabs;
import Button from 'antd/es/button';
import { ColumnsType } from 'antd/es/table/interface';
import moment from 'moment';
import { getStatusName } from 'seats/pages/CallTask/TaskTool';
import { GetCallRecordParams, TaskCallRecordInfo } from 'seats/schema/Task';
import { getCallRecordList } from 'seats/servers/servers';

import { clearNull, getTableIndex } from 'utils/tools';
import { CallRecordDetailDrawer } from 'components/CallRecordDetailDrawer';
import './style.scss';

const { RangePicker } = DatePicker;
interface CallRecordState {
  searchForm: any;
  tableData: TaskCallRecordInfo[];
  // 分页相关数据
  pageInfo: {
    pageTotal: number;
    pageNum: number;
    pageSize: number;
  };
  tableLoading: boolean;
  taskType: string; //taskType  任务类型 2：人机协同，3：人工自动外呼
}
/**任务通话记录页面 */
export default class CallRecord extends Component<{}, CallRecordState> {
  /**记录详情 */
  private callRecordRef: React.RefObject<CallRecordDetailDrawer>;
  /**表格列头 */
  private tableColumns: ColumnsType<TaskCallRecordInfo>;
  // 表单引用
  private formRef: React.RefObject<FormInstance>;
  constructor(props: {}) {
    super(props);
    this.callRecordRef = React.createRef();
    this.formRef = React.createRef();
    this.state = {
      searchForm: {},
      tableData: [],
      tableLoading: false,
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      taskType: '2',
    };
    this.tableColumns = [
      {
        title: '序号',
        key: 'index',
        dataIndex: 'index',
        fixed: 'left',
        width: 70,
        render: (text: any, record: TaskCallRecordInfo, index: number) =>
          getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
      },
      {
        title: '被叫号码',
        dataIndex: 'calledNumber',
        key: 'calledNumber',
      },
      {
        title: '号码ID',
        dataIndex: 'calledNumberId',
        key: 'calledNumberId',
      },
      {
        title: '主叫号码',
        dataIndex: 'callerNumber',
        key: 'callerNumber',
      },
      {
        title: '任务名称',
        dataIndex: 'taskName',
        key: 'taskName',
        width: 200,
        ellipsis: true,
      },
      {
        title: '任务当前状态',
        dataIndex: 'taskStatus',
        key: 'taskStatus',
        render: (text: any) => {
          return getStatusName(text);
        },
      },
      {
        title: '呼叫时间',
        dataIndex: 'callBeginTime',
        key: 'callBeginTime',
      },
      {
        title: '通话时长',
        dataIndex: 'callTalkTime',
        key: 'callTalkTime',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        fixed: 'right',
        render: (text: any, record: TaskCallRecordInfo, index: number) => {
          return (
            <>
              <Button
                type="link"
                onClick={() => {
                  this.showDetail(index, record);
                }}
              >
                详情
              </Button>
            </>
          );
        },
      },
    ];
    this.callback = this.callback.bind(this);
  }

  componentDidMount() {
    this.fetchList();
  }

  /**
   * 展开通话记录详情-公用外呼任务-通话记录详情组件
   */
  private showDetail(index: number, record: TaskCallRecordInfo) {
    const { pageInfo, searchForm, taskType } = this.state;
    const { pageNum, pageSize, pageTotal } = pageInfo;
    const searchParms = {
      ...searchForm,
      pageTotal,
      pageNo: (pageNum - 1) * pageSize + (index + 1), // 根据列表计算当前条位置
      pageSize: 1, // 按每条1页展示
      taskType,
    };
    this.callRecordRef.current?.show(searchParms, record);
  }

  /**
   * 查询table数据
   */
  private async fetchList() {
    this.setState({
      tableLoading: true,
    });
    const { pageInfo, searchForm, taskType } = this.state;
    try {
      const params: GetCallRecordParams = {
        ...searchForm,
        pageNo: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        taskType,
      };
      const res = await this.fetchCallRecord(params);
      pageInfo.pageTotal = res.count as number;
      this.setState({
        tableData: res.data,
        pageInfo: pageInfo,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      tableLoading: false,
    });
  }
  /**请求数据-单独，方便详情页调用 */
  private async fetchCallRecord(params: GetCallRecordParams) {
    const res = await getCallRecordList(clearNull(params));
    return res;
  }

  /**
   * 表格行操作后，重置列表
   */
  handleSearch = (values: any) => {
    const { phoneNumber, rangeTime } = values;
    const beginTime = rangeTime ? rangeTime[0].format('YYYY-MM-DD HH:mm:ss') : undefined;
    const endTime = rangeTime ? rangeTime[1]?.format('YYYY-MM-DD HH:mm:ss') : undefined;
    this.setState(
      {
        searchForm: { phoneNumber, beginTime, endTime },
      },
      () => {
        this.jumpPage(1);
      }
    );
  };
  /**
   * 重置搜索列表
   */
  handleReset = () => {
    this.formRef.current?.resetFields();
    this.setState(
      {
        searchForm: {},
      },
      () => {
        this.jumpPage(1);
      }
    );
  };
  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }

  // tab切换
  callback(key: string) {
    console.log(key);
    this.setState(
      {
        taskType: key,
      },
      () => {
        this.jumpPage(1);
      }
    );
  }

  render() {
    const {
      formRef,
      callRecordRef,
      tableColumns,
      state: {
        tableData,
        tableLoading,
        pageInfo: { pageNum, pageSize, pageTotal },
        taskType,
      },
    } = this;

    return (
      <div className="call-record">
        <Tabs activeKey={taskType} onChange={this.callback}>
          <TabPane tab="人机协同任务" key="2" />
          <TabPane tab="人工自动外呼任务" key="3" />
        </Tabs>
        <div className="mgr-header callrecord-header">
          <div className="mgr-header-left">
            <Form layout="inline" ref={formRef} onFinish={this.handleSearch}>
              <Form.Item
                label=""
                name="phoneNumber"
                getValueFromEvent={event => {
                  return event.target.value.replace(/[^0-9]+/g, '');
                }}
              >
                <Input style={{ width: 300 }} placeholder="请输入主叫号码或被叫号码" />
              </Form.Item>
              <Form.Item label="呼叫时间" name="rangeTime">
                <RangePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  ranges={{
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                  }}
                  allowClear
                />
              </Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
                <Button type="primary" ghost onClick={this.handleReset}>
                  重置
                </Button>
              </Space>
            </Form>
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            dataSource={tableData}
            scroll={{ x: 'max-content' }}
            columns={tableColumns}
            rowKey="callRecordId"
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
        <CallRecordDetailDrawer ref={callRecordRef} fetchRecord={this.fetchCallRecord.bind(this)} />
      </div>
    );
  }
}
